﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;

/// <summary>
///TreeControl 的摘要说明
/// </summary>
public class TreeControl
{
	public TreeControl()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}
    /// <summary>
    /// 初始化树
    /// </summary>
    /// <param name="treeView"></param>
    /// <param name="ds"></param>
    public static void InitTree(TreeView treeView, DataSet ds)
    {
        treeView.Nodes.Clear();
        ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["id"], ds.Tables[0].Columns["parent_id"], false);

        foreach (DataRow dbRow in ds.Tables[0].Rows)
        {
            if (dbRow["parent_id"].ToString() == "0")
            {
                TreeNode newNode = CreateNode(dbRow["title"].ToString(), dbRow["id"].ToString(), dbRow["action"].ToString());
                treeView.Nodes.Add(newNode);
                SubTree(dbRow, newNode);
            }
        }
        treeView.ExpandAll();
    }
    /// <summary>
    /// 构建子节点
    /// </summary>
    /// <param name="dbRow"></param>
    /// <param name="node"></param>
    private static void SubTree(DataRow dbRow, TreeNode node)
    {
        foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))
        {
            TreeNode childNode = CreateNode(childRow["title"].ToString(), childRow["id"].ToString(), childRow["action"].ToString());
            node.ChildNodes.Add(childNode);
            SubTree(childRow, childNode);
        }
    }
    /// <summary>
    /// 创建节点
    /// </summary>
    /// <param name="text"></param>
    /// <param name="tag"></param>
    /// <param name="url"></param>
    /// <returns></returns>
    private static TreeNode CreateNode(string text, string tag, string url)
    {
        TreeNode node = new TreeNode();
        node.Text = text;
        node.Value = tag;
        node.NavigateUrl = url;
        return node;
    }
}